package com.fablesoft.projectdatacollect.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fablesoft.projectdatacollect.album.PreviewImageActivity;
import com.fablesoft.projectdatacollect.album.ShowAllPhotoActivity;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.FileBean;
import com.fablesoft.projectdatacollect.bean.FileListResponse;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.http.HttpUploadThread;
import com.fablesoft.projectdatacollect.http.HttpUploadThread.PrepareUpload;
import com.fablesoft.projectdatacollect.util.BitmapUtil;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.Log4jUtil;
import com.fablesoft.projectdatacollect.util.StoragePathsManager;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class PhotoActivity extends BaseRequestActivity {

	public static List<View> imageList = null;
	private DisplayImageOptions mOptions;
//	private static final int MAX_COUNT = 9;
	private static final int PICK_IMAGE_CODE = 0;
	private static final int PREVIEW_IMAGE_CODE = 1;
	private final static int UPLOAD_IMAGE_REQUEST = 101;
	private final static int UPLOAD_INFO_REQUEST = 102;
	public final static int DELETE_IMAGE_REQUEST = 103;
	private int requestType;
	private GridView reportGridView;
	private MyBaseAdapter mAdapter;
	private int imageWidth = 0;
//	private int addImageWidth = 0;
	private View addImageView;
	private File tempFile;
//	private EditText reportContent;
	private ArrayList<FileBean> files;
	private String id;
//	private int deletePosition;
	private String fileId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo);
		DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
		int dp20 = Math.round(TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 20, displayMetrics));
		imageWidth = (displayMetrics.widthPixels - dp20 * 3)  / 4;
//		addImageWidth = imageWidth - dp20 / 20;
		Intent intent = getIntent();
		files = (ArrayList<FileBean>) getIntent().getSerializableExtra("files");
		id = intent.getStringExtra("id");
		initView();
	}

	private void initView() {
		View back = findViewById(R.id.back);
		back.setOnClickListener(mClickListener);
		if (mOptions == null) {
			mOptions = new DisplayImageOptions.Builder()
					.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
					// .showImageOnLoading(R.drawable.default_image_bg)
					.resetViewBeforeLoading(false).cacheOnDisc(true)
					.bitmapConfig(Bitmap.Config.RGB_565)
					.cacheInMemory(true)
					.considerExifParams(true).build();
		}
		imageList = new ArrayList<View>();
		mAdapter = new MyBaseAdapter();
		reportGridView = (GridView) findViewById(R.id.edit_show_grid_view);
		reportGridView.setAdapter(mAdapter);
		reportGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0) {
					Intent intentFromGallery = new Intent(PhotoActivity.this,
							ShowAllPhotoActivity.class);
					intentFromGallery.putExtra("count", 6);
					startActivityForResult(intentFromGallery, PICK_IMAGE_CODE);
				} else {
					Intent intent = new Intent(PhotoActivity.this,
							PreviewImageActivity.class);
					intent.putExtra("location", position - 1);
					intent.putExtra("isShow", true);
					startActivityForResult(intent, PREVIEW_IMAGE_CODE);
				}
			}
		});
		int h = (int) (imageWidth * 0.7);
		if(imageList.size() == 0){
			addImageView = LayoutInflater.from(PhotoActivity.this).inflate(
					R.layout.image_add, null);
			addImageView.setLayoutParams(new AbsListView.LayoutParams(imageWidth,
					h));
			ImageView imageView = (ImageView) addImageView
					.findViewById(R.id.upload_btn);
			imageView.setLayoutParams(new RelativeLayout.LayoutParams(
					imageWidth, h));
			imageList.add(addImageView);
		}
		if(files != null && files.size() > 0){
			for (int i = 0; i < files.size(); i++) {
				View v = LayoutInflater.from(PhotoActivity.this)
						.inflate(R.layout.image_layout, null);
				ImageView imageView = (ImageView) v
						.findViewById(R.id.image);
				View deleteBtn = v.findViewById(R.id.image_delete_btn);
				deleteBtn.setOnTouchListener(mOnClickListener);
				v.setLayoutParams(new AbsListView.LayoutParams(
						imageWidth, h));
				ImageLoader.getInstance().displayImage(
						Config.BASE + files.get(i).getFilePath(),
						imageView, mOptions);
				Map<String, String> imageInfo = new HashMap<String, String>();
				imageInfo.put("localUri",files.get(i).getFilePath());
				imageInfo.put("fid", files.get(i).getId());
				v.setTag(imageInfo);
				imageList.add(v);
//				deleteBtn.setTag(v);
			}
		}
	}

	private OnTouchListener mOnClickListener = new OnTouchListener() {
//		@Override
//		public void onClick(final View v) {
//			
//		}
		@Override
		public boolean onTouch(final View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				createPromptDialog(PhotoActivity.this, null, "确定删除?", null, null, new ConfirmClickListener() {
					@Override
					public void confirmClickImp() {
						createLoadingDialog(PhotoActivity.this);
						showDialog("删除中");
						View image = (View)v.getParent();
						Map<String, String> imageInfo = (Map<String, String>) image.getTag();
						fileId = imageInfo.get("fid");
						Map<String, Object> params = new HashMap<String, Object>();
						new HttpThread(Config.DELETE_FILE_URL + "?fileId=" + fileId, new HttpListener() {
							@Override
							public void onRequestFinish(BaseResponse response) {
								Message msg = mHandler.obtainMessage();
								msg.obj = response;
								msg.what = DELETE_IMAGE_REQUEST;
								mHandler.sendMessage(msg);
							}
							
							@Override
							public void onNotLogin(BaseResponse response) {
								PhotoActivity.this.onNotLogin(response);
							}
						}, params, BaseResponse.class).start();
					}
				});
				break;

			default:
				break;
			}
			return false;
		}
	};
	
	private class MyBaseAdapter extends BaseAdapter {
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
//			if(position > 0){
//				View deleteBtn = imageList.get(position).findViewById(R.id.image_delete_btn);
//				deleteBtn.setTag(position);
//				deleteBtn.setOnClickListener(null);
//				deleteBtn.setOnClickListener(mOnClickListener);
//			}
			return imageList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public int getCount() {
			int count = imageList == null ? 0 : imageList.size();
//			if (count > MAX_COUNT) {
//				count = MAX_COUNT;
//			}
			return count;
		}
	};

	private OnClickListener mClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.back:
				setResult(201);
				finish();
				break;
			}
		}
	};

	@Override
	public void onBackPressed() {
		setResult(201);
		finish();
	};
	
//	private void reportData() {
//		String content = reportContent.getText().toString().trim();
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("nr", content);
//		StringBuffer fids = new StringBuffer("");
//		for (int i = 0; i < imageList.size(); i++) {
//			if (imageList.get(i).getTag() != null) {
//				Map<String, String> imageInfo = (HashMap<String, String>) imageList
//						.get(i).getTag();
//				fids.append(imageInfo.get("fid")).append(";");
//			}
//		}
//		if (fids.length() > 0) {
//			params.put("fids", fids.substring(0, fids.length() - 1));
//		}else{
//			params.put("fids", "");
//		}
//		requestType = UPLOAD_INFO_REQUEST;
//		sendRequest(Config.LOGIN_URL, params,
//				BaseResponse.class);
//		createLoadingDialog(this);
//		showDialog("提交中");
//	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		if (resultCode != Activity.RESULT_CANCELED) {
			switch (requestCode) {
			case PICK_IMAGE_CODE:
				createLoadingDialog(PhotoActivity.this);
				showDialog("上传中");
				PrepareUpload prepareUpload = new PrepareUpload() {
					@Override
					public List<File> doBeforeUpload() {
						List<File> files = new ArrayList<File>();
						for (int i = 0; i < ShowAllPhotoActivity.tempSelectBitmap
								.size(); i++) {
							File file = getFile(
									ShowAllPhotoActivity.tempSelectBitmap
											.get(i).getImagePath(), i + "");
							if (file != null) {
								files.add(file);
							}
						}
						return files;
					}
				};
				Map<String, Object> uploadFileparams = new HashMap<String, Object>();
				Log.i("luzx", "id:" + id);
				uploadFileparams.put("folderName", "safeActivity");
				uploadFileparams.put("safeActivityId", id);
				HttpUploadThread httpUploadThread = new HttpUploadThread(
						Config.SIGN_IN_UPLOAD_FILES_URL, new HttpListener() {
							@Override
							public void onRequestFinish(BaseResponse response) {
								if (tempFile != null && tempFile.exists()) {
									// 删除临时图片
									File[] files = tempFile.listFiles();
									for (int j = 0; j < files.length; j++) {
										// 删除子文件
										if (files[j].isFile()) {
											files[j].delete();
										}
									}
								}
								Message msg = mHandler.obtainMessage();
								msg.obj = response;
								msg.what = UPLOAD_IMAGE_REQUEST;
								mHandler.sendMessage(msg);
							}

							@Override
							public void onNotLogin(BaseResponse response) {
								PhotoActivity.this.onNotLogin(response);
							}
						}, uploadFileparams, FileListResponse.class, prepareUpload);
				MyApplication.getInstance().getRequestQueue()
						.execute(httpUploadThread);
				break;
			case PREVIEW_IMAGE_CODE:
				if (mAdapter != null) {
					mAdapter.notifyDataSetChanged();
				}
				break;
			}
		}
	}

	private File getFile(String path, String tempName) {
		StoragePathsManager mStoragePathsManager = new StoragePathsManager(this);
		String tempPath = mStoragePathsManager.getInternalStoragePath()
				+ "/pingan/uplaod/temp/";
		Bitmap bitmap = null;
		tempFile = new File(tempPath);
		if (!tempFile.exists()) {
			tempFile.mkdirs();
		}
		File file = null;
		Log.i("lzx", "imagePath:" + path);
		try {
			file = new File(path);
			if (BitmapUtil.isNeedScale(file, 600, 800)) {
				bitmap = BitmapUtil.decodeThumbBitmapForFile(path, 600, 800);
				file = new File(tempPath + tempName + ".jpg");
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
						new FileOutputStream(file));
				bitmap.recycle();
				bitmap = null;
				System.gc();
			}
		} catch (Exception e) {
			Log4jUtil.e(e.toString());
			e.printStackTrace();
			file = null;
			ShowAllPhotoActivity.tempSelectBitmap.clear();
//			ShowAllPhotoActivity.tempSelectBitmap = null;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(PhotoActivity.this, "上传失败,图片不存在",
							Toast.LENGTH_SHORT).show();
				}
			});
			Log.i("lzx", "上传失败,图片不存在");
			// 删除临时图片
			File[] files = tempFile.listFiles();
			if (files != null) {
				for (int j = 0; j < files.length; j++) {
					// 删除子文件
					if (files[j].isFile()) {
						files[j].delete();
					}
				}
			}
			// return result;
		}

		return file;
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			dismissDialog();
			if (msg.obj == null) {
				Toast.makeText(PhotoActivity.this, R.string.request_error,
						Toast.LENGTH_SHORT).show();
				return;
			}
			switch (msg.what) {
			case UPLOAD_IMAGE_REQUEST:
				FileListResponse result = (FileListResponse) msg.obj;
				ShowAllPhotoActivity.tempSelectBitmap.clear();
				if (result.getSuccess()) {
					for (int i = 0; i < result.getData().length; i++) {
						View v = LayoutInflater.from(PhotoActivity.this)
								.inflate(R.layout.image_layout, null);
						ImageView imageView = (ImageView) v
								.findViewById(R.id.image);
						View deleteBtn = v.findViewById(R.id.image_delete_btn);
						deleteBtn.setOnTouchListener(mOnClickListener);
						int h = (int) (imageWidth * 0.7);
						v.setLayoutParams(new AbsListView.LayoutParams(
								imageWidth, h));
						ImageLoader.getInstance().displayImage(
								Config.BASE + result.getData()[i].getFilePath(),
								imageView, mOptions);
						Map<String, String> imageInfo = new HashMap<String, String>();
						imageInfo.put("localUri", result.getData()[i].getFilePath());
						imageInfo.put("fid", result.getData()[i].getId());
						v.setTag(imageInfo);
						imageList.add(v);
//						deleteBtn.setTag(v);
					}
					if (mAdapter != null) {
						mAdapter.notifyDataSetChanged();
					}
				} else {
					Toast.makeText(PhotoActivity.this, result.getMessage(),
							Toast.LENGTH_SHORT).show();
				}
//				ShowAllPhotoActivity.tempSelectBitmap = null;
				break;

			case DELETE_IMAGE_REQUEST:
				dismissDialog();
				BaseResponse baseResponse = (BaseResponse) msg.obj;
				if (baseResponse.getSuccess()) {
					for(View v : imageList){
						Map<String, String> imageInfo = (Map<String, String>) v.getTag();
						if(imageInfo != null && fileId.equals(imageInfo.get("fid"))){
							imageList.remove(v);
							break;
						}
					}
					if (mAdapter != null) {
						mAdapter.notifyDataSetChanged();
					}
				}
				Toast.makeText(PhotoActivity.this, baseResponse.getMessage(),
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

//	@Override
//	public void onRequestFinish(BaseResponse response) {
//		Message msg = mHandler.obtainMessage();
//		switch (requestType) {
//		case UPLOAD_INFO_REQUEST:
//			msg.what = UPLOAD_INFO_REQUEST;
//			requestType = -1;
//			break;
//		}
//		msg.obj = response;
//		mHandler.sendMessage(msg);
//	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
